package com.summli.basic.class04;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 定义比较器，对于比较的排序，可以通过比较器来决定比较的内容，可以指定泛型，并且可以决定升序还是降序
 */
public class Code01_Comparator {
    public static class Student {
        public String name;
        public int id;
        public int age;

        public Student(String name, int id, int age) {
            this.name = name;
            this.id = id;
            this.age = age;
        }
    }

    public static class IdAscendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return o1.id-o2.id;
        }
    }

    public static class IdDescComparator implements Comparator<Student>{

        @Override
        public int compare(Student o1, Student o2) {
            return o2.id-o1.id;
        }
    }

    public static class AComp implements Comparator<Integer>{

        // 如果返回负数，认为第一个参数应该拍在前面
        // 如果返回正数，认为第二个参数应该拍在前面
        // 如果返回0，认为谁放前面都行
        @Override
        public int compare(Integer arg0, Integer arg1) {

            return arg1 - arg0;

//			return 0;
        }

    }
    public static void printStudents(Student[] students) {
        for (Student student : students) {
            System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
        }
    }
    public static void main(String[] args) {
        Integer[] arr = {5,4,3,2,7,9,1,0};

        Arrays.sort(arr, new AComp());// arrays.sort()：默认是升序，如果可以通过比较器改为降序

        for(int i = 0 ;i < arr.length;i++) {
            System.out.println(arr[i]);
        }

        System.out.println("===========================");

        Student student1 = new Student("A", 2, 20);
        Student student2 = new Student("B", 3, 21);
        Student student3 = new Student("C", 1, 22);

        Student[] students = new Student[] { student1, student2, student3 };
        System.out.println("第一条打印");


        Arrays.sort(students, new IdAscendingComparator());


        printStudents(students);
        System.out.println("===========================");
        System.out.println("第二条打印");


        Arrays.sort(students, new IdDescComparator());


        printStudents(students);
        System.out.println("===========================");
    }
}
